from __future__ import with_statement
import webapp2
import model
import urllib

import os
import json
import logging 
import math
import jinja2
import mailer
#import logging

from google.appengine.ext import ndb
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers


from google.appengine.api import files
from google.appengine.api import users
from google.appengine.api import images
from google.appengine.api import urlfetch

#import mailer

j_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class DefaultHandler(webapp2.RequestHandler):

    def __init__(self, request, response):
        self.initialize(request, response)
        

    def get(self):
        template = j_env.get_template('templates/get.html')
        html = template.render()
        self.response.out.write(html)

    def post(self):
        the_title = self.request.get('room_title')
        the_description = self.request.get('room_description')
        the_price = self.request.get('room_price')
        the_location = self.request.get('room_location')
            
        new_room = model.RoomProfiles()
        new_room.title = the_title
        new_room.description = the_description
        new_room.price = int(the_price, base=10)
        new_room.location = the_location
        new_room.google_id = users.get_current_user()
#        new_room.latitude = 52.789995,-6.875896
 #       new_room.longitude = -6.875896,52.789995
  #      
   #     http://maps.googleapis.com/maps/api/geocode/json?latlng=52.789995,-6.875896&sensor=true
  #  https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-6.875896,52.789995&radius=500&sensor=false&key=AIzaSyBYsOHaKe8cVBWocDa5vRq1QKbdZQeflfw    
   # https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyBYsOHaKe8cVBWocDa5vRq1QKbdZQeflfw
    #https://map.googleapis.com/maps/api/place/textsearch/json?input=1600+Amp&key=AIzaSyBYsOHaKe8cVBWocDa5vRq1QKbdZQeflfwr&sensor=true
        new_room.put()
    
class ShowRoomsHandler(webapp2.RequestHandler):
    def __init__(self, request, response):
        self.initialize(request, response)
        
        url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=52.789995,-6.875896&sensor=true"
        result = urlfetch.fetch(url,method=urlfetch.GET)
        if result.status_code == 200:
            sv = result.content

            found=0
            count = 0
            jsonData = json.loads(sv)
            retrieved_json = jsonData['results']
            while found == 0:
                if retrieved_json[0]['address_components'][count]['types'][0].encode('utf8') == 'administrative_area_level_1':
                    location_area_level_one = retrieved_json[0]['address_components'][count]['long_name'].encode('utf8')
                    found =1
                count +=1


class RoomSearchHandler(webapp2.RequestHandler):
    def get(self):
        self.response.out.write('photo added')    
                
    def post(self):
    
        bool = 1
        data = self.request.body
        jsonData = json.loads(data)
        
        try:
            searchItem=jsonData['location']
            logging.info('The search location is: ' + jsonData['location'])
            
        except:
            bool = 0
            pass
            
        if bool == 1:
            current_rooms = model.RoomProfiles.query().filter(model.RoomProfiles.location == jsonData['location'])
            logging.info("test 2")
            room_keys=[]
            for room in current_rooms:
                room_keys.append(room.key.urlsafe())

            self.response.headers['Content-Type'] = "application/json"
            self.response.out.write(json.dumps(room_keys))
            
        elif bool == 0:
            logging.info('checking key : ' + jsonData['roomKey'])
            rev_key = ndb.Key(urlsafe=jsonData['roomKey'])
            logging.info(jsonData['roomKey'])
            revesion = rev_key.get()
            logging.info(revesion.title)
           # logging.info(revesion.preferred_age)
            s={'title': revesion.title,'description' : revesion.description,'price' : revesion.price,
               'location' : revesion.location, 'pic_url': revesion.image_url, 'house_type': revesion.house_type, 
               'room_type': revesion.room_type, 'bathroom_count': revesion.bathroom_count, 'smoking': revesion.smoking,
               'gender': revesion.preferred_gender, 'age': revesion.preferred_age, 'tv': revesion.television,
               'sky_cable': revesion.sky_cable, 'onsuite': revesion.onsuite, 'internet': revesion.internet, 
               'heating': revesion.heating,'user_id': revesion.google_id.nickname(), 'air_con': revesion.air_con}
            logging.info(revesion.description)
            logging.info(revesion.price)
            self.response.headers['Content-Type'] = "application/json"
            self.response.out.write(json.dumps(s))

class RoomGpsHandler(webapp2.RequestHandler):
    def post(self):
        data = self.request.body
        jsonData = json.loads(data)
        lat = jsonData['latitude']
        logging.info('lat :' + lat)
         
        lon = jsonData['longitude']
        logging.info('lon : ' + lon)
        url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lon + "," + lat + "&sensor=true"
        logging.info('url : ' + url)
        maxDistance = int(jsonData['max_distance'])
        logging.info('max distance :' + str(maxDistance))
        result = urlfetch.fetch(url,method=urlfetch.GET)
        if result.status_code == 200:
            sv = result.content

            found=0
            count = 0
            jsonData = json.loads(sv)
            retrieved_json = jsonData['results']
            while found == 0:
                if retrieved_json[0]['address_components'][count]['types'][0].encode('utf8') == 'administrative_area_level_1':
                    location_area_level_one = retrieved_json[0]['address_components'][count]['long_name'].encode('utf8')
                    found =1
                count +=1
            current_rooms = model.RoomProfiles.query().filter(model.RoomProfiles.location == location_area_level_one.lower())
            logging.info("test 2")
            room_keys=[]
            if maxDistance == 0:
                mindistance= 5.0
            elif maxDistance == 1:
                mindistance=10.0
            else:
                mindistance=15.0
            for room in current_rooms:
                logging.info("lat1:" + lat)
                logging.info("lon1:" + lon)
                logging.info("lat2:" + str(room.latitude))
                logging.info("lon2:" + str(room.longitude))
                distance = float(distance_on_unit_sphere(float(lon),float(lat),float(room.latitude),float(room.longitude)))
                #logging.info("distance :" + distance)
                distance *=  3960
                #room.key.urlsafe('distance')
                logging.info(distance)
                if distance <= mindistance:
                    room_keys.append(room.key.urlsafe())
                    logging.info('urlKey :' + room.key.urlsafe())

            self.response.headers['Content-Type'] = "application/json"
            self.response.out.write(json.dumps(room_keys))
            

def distance_on_unit_sphere(lat1, long1, lat2, long2):

    degrees_to_radians = math.pi/180.0
        
    # phi = 90 - latitude
    phi1 = (90.0 - lat1)*degrees_to_radians
    phi2 = (90.0 - lat2)*degrees_to_radians
        
    # theta = longitude
    theta1 = long1*degrees_to_radians
    theta2 = long2*degrees_to_radians
    
    cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + 
           math.cos(phi1)*math.cos(phi2))
    arc = math.acos( cos )
    return arc

class PhotoUploadFormHandler(webapp2.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload_photo')
        # The method must be "POST" and enctype must be set to "multipart/form-data".
        self.response.out.write('<html><body>')
        self.response.out.write('<form action="%s" method="post" enctype="multipart/form-data">' % upload_url)
        self.response.out.write('''Upload File: <input type="file" name="file"><br> <input type="submit"
            name="submit" value="Submit"> </form></body></html>''')

class PhotoUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        logging.info('\n\nuploading image\n\n')
        
        ff= model.UserPhoto()
        ff.user = 'tom'
        ff.put()
    
        room_image= model.UserPhoto()
    
        try:
            logging.info('\n\nRetrieving image from self\n\n')
            upload_files = self.get_uploads('file')
            blob_info = upload_files[0]
            logging.info('\n\nRetrieved file from form\n\n')
            room_image.name = users.get_current_user()
            
            room_image.blob_key = blob_info.key() 
            room_image.put()
            current_room = model.RoomProfiles.query().filter(model.RoomProfiles.google_id ==users.get_current_user()).fetch(1)
            for room in current_room:    
                #room.room_image= blob_info.key()
                room.image_url = '%s' % images.get_serving_url(blob_info.key(), 0)
                room.put()
            i = 34
            p = 44
            p = i + p
            
            self.redirect('/json/generate_rooms' % blob_info.key())
            
        except:
            self.redirect('/json/generate_rooms' )
            
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self,resource):
        self.response.out.write("%s %s %s" % (images.get_serving_url(resource),
        images.get_serving_url(resource, 150),
        images.get_serving_url(resource, 80)))
    
    def post(self, photo_key):
        if not blobstore.get(photo_key):
            logging.info('serverhandler been accessed')
            self.error(404)
        else:
            

           self.response.out.write("%s %s %s" % (images.get_serving_url(photo_key, 32),
                                                 images.get_serving_url(photo_key, 150),
                                                 images.get_serving_url(photo_key, 80)))

class PhotoDownloadFormHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        logging.info('test1')
        resource = str(urllib.unquote(resource))
        logging.info('test2')
        blob_info = blobstore.BlobInfo.get(resource)
        logging.info('test3')
        tim = images.get_serving_url(resource,crop=False, secure_url=True)
        logging.info('test4')
        self.send_blob(tim)
        
class SendMessageHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def post(self):
        data = self.request.body
        jsonData = json.loads(data)
        
        
        message_to = jsonData['message_to']
        logging.info('Message sent to: ' + message_to)
        message_from = jsonData['message_from']
        logging.info('Message sent from: ' + message_from)
        message_subject = jsonData['message_subject']
        logging.info('Message subject: ' + message_subject)
        message_content = jsonData['message_content']
        logging.info('Message content: ' + message_content)
        try:
            current_message = model.messageArchive()
            current_message.message_to = message_to
            current_message.message_from = message_from
            current_message.message_content = message_content
            current_message.message_subject = message_subject
            current_message.put()
            
            mailer.send_room_request_email(message_to, 
                               message_from)
            self.response.out.write(200)
        except Exception as inst:
            logging.error(inst)
            logging.error(inst.args)
            self.response.out.write(300)
            
           

app = webapp2.WSGIApplication([
                               ('/image/thumbnail/([^/]+)?', PhotoDownloadFormHandler),
                                ('/upload_form', PhotoUploadFormHandler),
                                ('/upload_photo', PhotoUploadHandler),
                                ('/serve/([^/]+)?', ServeHandler),
                                ('/post', ShowRoomsHandler),
                                ('/send_message', SendMessageHandler),
                                ('/generate_rooms/gps', RoomGpsHandler),
                                ('/generate_rooms/search', RoomSearchHandler),
                                ('/.*', DefaultHandler),
                                ],debug=True)    